package com.iflytek.ossp.shiro;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import com.iflytek.ossp.auth.entity.MenuInfo;
import com.iflytek.ossp.auth.entity.RoleInfo;
import com.iflytek.ossp.auth.entity.UserInfo;
import com.iflytek.ossp.auth.service.MenuService;
import com.iflytek.ossp.auth.service.RoleService;
import com.iflytek.ossp.auth.service.UserService;

public class OsspDbRealm extends AbstractDbRealm {

	@Resource
	private UserService userService;

	@Resource
	private RoleService roleService;

	@Resource
	private MenuService menuService;

	protected Collection<String> getRoleNames(String loginName) {
		Collection<String> roles = new HashSet<String>();
		UserInfo userInfo = userService.getUserByLoginName(loginName);
		if (userInfo == null) {
			return roles;
		}
		List<RoleInfo> roleInfos = roleService.getRolesByUser(userInfo.getId());
		for (RoleInfo roleInfo : roleInfos) {
			roles.add(roleInfo.getName());
		}
		return roles;
	}

	protected Collection<String> getPermissionNames(String loginName) {
		Collection<String> permissions = new HashSet<String>();
		UserInfo userInfo = userService.getUserByLoginName(loginName);
		if (userInfo == null) {
			return permissions;
		}
		List<MenuInfo> menuInfos = menuService.getMenusByUser(userInfo.getId());
		for (MenuInfo menuInfo : menuInfos) {
			if (Integer.valueOf(MenuInfo.MENU_TYPE_ACTION).equals(
					menuInfo.getMenuType())) {
				permissions.add(menuInfo.getName());
			}
		}
		return permissions;
	}

	protected String getPassword(String loginName) {
		return userService.getUserByLoginName(loginName).getPassword();
	}

	protected ShiroUser getShiroUser(String loginName) {
		UserInfo userInfo = userService.getUserByLoginName(loginName);
		ShiroUser su = new ShiroUser();
		su.setId(userInfo.getId());
		su.setAreaId(Long.valueOf(userInfo.getArea().getAiid()));
		su.setLoginName(userInfo.getLoginName());
		su.setName(userInfo.getTrueName());
		return su;
	}

}
